package com.qf.pojo.controller;

import com.qf.pojo.mapper.TicketMapper;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.spring.boot.CuratorZkTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/ticket")
public class TicketController {

    @Autowired
    private CuratorZkTemplate curatorZkTemplate;

    @Value("${windnum}")
    private String windNum;

    @Autowired
    private TicketMapper ticketMapper;

    @GetMapping("/sell/{id}")
    public void sellTicket(@PathVariable Integer id) throws Exception {
        while (true){
            //获取所对象(锁的名字应该写啥？？？卖相同票才互斥)
            InterProcessLock lock = curatorZkTemplate.getSharedReentrantLock("/" + id);

            try {
                //加锁
                lock.acquire();
                //查询对应id的票数
                Integer count = ticketMapper.findCountById(id);
                if (count > 0) {
                    System.out.println(windNum + "正在卖" + count + "号票");
                    Thread.sleep(500);

                    count--;
                    ticketMapper.updateCountById(id, count);
                    System.out.println(windNum + "卖完后还剩余" + count + "张票");
                } else {
                    break;
                }
            }finally {
                //释放锁
                lock.release();
            }
        }
    }
}
